<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="班级码" prop="classCode">
        <el-input v-model="queryParams.classCode" placeholder="请输入班级码" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="班级名称" prop="className">
        <el-input v-model="queryParams.className" placeholder="请输入班级名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="班级类型" prop="type">
        <el-select v-model="queryParams.type" placeholder="选择" clearable :style="{ width: '100%' }">
          <el-option label="普通型" value="0"></el-option>
          <el-option label="学习型" value="1"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="是否加密" prop="encrypted">
        <el-select v-model="queryParams.encrypted" placeholder="选择" clearable :style="{ width: '100%' }">
          <el-option label="加密" value="1"></el-option>
          <el-option label="未加密" value="0"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="群主ID" prop="createdBy">
        <el-input v-model="queryParams.createdBy" placeholder="群主ID" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['classes:Class:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['classes:Class:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['classes:Class:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['classes:Class:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="ClassList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="班级id" align="center" prop="id" />
      <el-table-column label="班级码" align="center" prop="classCode" />
      <el-table-column label="班级名称" align="center" prop="className" />
      <el-table-column label="班级头像" align="center" prop="classAvatar">
        <template slot-scope="scope">
          <el-popover placement="top-start" title="" trigger="hover">
            <img :src="scope.row.classAvatar" alt="" style="width: 150px;height: 150px">
            <img slot="reference" :src="scope.row.classAvatar" style="width: 50px;height: 50px">
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column label="类型" align="center" prop="type">
        <template slot-scope="scope">
          <span v-if="scope.row.type == '0'">普通型</span>
          <span v-if="scope.row.type == '1'">学习型</span>
        </template>
      </el-table-column>
      <el-table-column label="是否加密" align="center" prop="encrypted">
        <template slot-scope="scope">
          <span v-if="scope.row.encrypted == '1'">加密</span>
          <span v-if="scope.row.encrypted == '0'">未加密</span>
        </template>
      </el-table-column>
      <el-table-column label="班级密码" align="center" prop="password" />
      <el-table-column label="群主ID" align="center" prop="createdBy" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-dropdown size="mini" @command="(command) => handleCommand(command, scope.row)"
            v-hasPermi="['course:chapter:edit', 'course:course:edit']">
            <el-button size="mini" type="text" icon="el-icon-d-arrow-right">更多</el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="handleClassUser" icon="el-icon-key">查看班级成员
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['classes:Class:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['classes:Class:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改班级对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="班级名称" prop="className">
          <el-input v-model="form.className" placeholder="请输入班级名称" />
        </el-form-item>
        <el-form-item label="类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择">
            <el-option label="普通型" value="0"></el-option>
            <el-option label="学习型" value="1"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="上传班级头像" prop="classAvatar">
          <el-upload ref="upload" style="display: inline" drag action="" :http-request="handleUpload"
            :auto-upload="false" multiple :limit="1" list-type="picture">
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
          </el-upload>
          <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上传到服务器</el-button>
        </el-form-item>
        <el-form-item label="是否加密" prop="encrypted">
          <el-select v-model="form.encrypted" placeholder="请选择">
            <el-option label="加密" value="1"></el-option>
            <el-option label="不加密" value="0"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-if="form.encrypted == 1" label="班级密码" prop="password">
          <el-input v-model="form.password" placeholder="请输入班级密码" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listClass, getClass, delClass, addClass, updateClass } from "@/api/classes/Class";
import { getFileMD5, getBaseUrl, addFile } from "@/api/file/file";

export default {
  name: "Class",
  data() {
    return {
      upload: null,
      fileList: [],
      baseUrl: "",
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 班级表格数据
      ClassList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        classCode: null,
        className: null,
        classAvatar: null,
        type: null,
        encrypted: null,
        password: null,
        createdBy: null,
        deleteFlag: null
      },
      // 表单参数
      form: {
        classAvatar: "",
      },
      // 表单校验
      rules: {
        classCode: [
          { required: true, message: "班级码，UUID不能为空", trigger: "blur" }
        ],
        className: [
          { required: true, message: "班级名称不能为空", trigger: "blur" }
        ],
        classAvatar: [
          { required: true, message: "班级头像url不能为空", trigger: "blur" }
        ],
        type: [
          { required: true, message: "类型，普通型0，学习型1不能为空", trigger: "change" }
        ],
        encrypted: [
          { required: true, message: "是否被加密，加密1，未加密0不能为空", trigger: "blur" }
        ],
        createdBy: [
          { required: true, message: "被谁创建的, 群主不能为空", trigger: "blur" }
        ],
        deleteFlag: [
          { required: true, message: "删除标志不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    // 命令
    handleCommand(command, row) {
      switch (command) {
        case "handleClassUser":
          this.handleClassUser(row);
          break;
        default:
          break;
      }
    },
    handleClassUser(row) {
      const classId = row.id;
      console.log(classId)
      this.$router.push("/class/class-user/" + classId);
    },
    submitUpload() {
      this.$refs.upload.submit();
    },
    handleUpload(param) {
      let file = param.file;
      getFileMD5(file).then(res => {
        let fileMd5 = res.msg
        addFile(file, fileMd5).then(response => {
          console.log(response)
          this.form.classAvatar = this.baseUrl + response.url
          this.$modal.msgSuccess("新增成功");
          this.upload = null;
          this.fileList = [];
        });
      })
    },
    /** 查询班级列表 */
    getList() {
      this.loading = true;
      listClass(this.queryParams).then(response => {
        this.ClassList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
      getBaseUrl().then(res => {
        this.baseUrl = res.msg;
      })
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        classCode: null,
        className: null,
        classAvatar: null,
        type: null,
        encrypted: null,
        password: null,
        createdBy: null,
        deleteFlag: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加班级";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getClass(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改班级";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateClass(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addClass(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除班级编号为"' + ids + '"的数据项？').then(function () {
        return delClass(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('classes/Class/export', {
        ...this.queryParams
      }, `Class_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
